# 封装公共断言方法
import json

import pymysql

import app


def common_assert(testCase, response, exp_success, exp_code, exp_message):
    res_dict = response.json()
    # 断言
    # 断言响应体的响应码
    testCase.assertEqual(200, response.status_code)
    # 断言响应体字典的值
    testCase.assertEqual(exp_success, res_dict.get("success"))
    testCase.assertEqual(exp_code, res_dict.get("code"))
    testCase.assertIn(exp_message, res_dict.get("message"))


# 数据库初始化的封装
class DBUtil:
    __conn = None
    __cur = None

    # 创建数据库连接对象
    @classmethod
    def __get_connect(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host="211.103.136.244",
                                         user="student",
                                         password="iHRM_student_2021",
                                         database="ihrm",
                                         port=7061)
        return cls.__conn

    # 创建游标对象
    @classmethod
    def __get_cursor(cls):
        if cls.__cur is None:
            cls.__cur = cls.__get_connect().cursor()
        return cls.__cur

    # 执行SQL语句(业务SQL语句)
    @classmethod
    def exe_sql(cls, sql_str):
        try:
            # 获取游标对象
            cur = cls.__get_cursor()
            # 在游标对象中执行SQL语句
            cur.execute(sql_str)
            # 如果是查询语句，返回全部结果
            if sql_str.split(" ")[0].lower() == "select":
                return cur.fetchall()
            # 如果是非查询语句
            else:
                # 手动数据库事务提交
                cls.__get_connect().commit()
                # 返回受影响的行数
                return "受影响的行数:{}".format(cur.rowcount)
        except Exception as e:
            # 事务的回滚
            cls.__get_connect().rollback()
            print(e)
        finally:
            # 关闭游标对象
            cls.__close_cursor()
            # 关闭数据库连接对象
            cls.__close_connect()

    # 关闭游标对象
    @classmethod
    def __close_cursor(cls):
        if cls.__cur is not None:
            cls.__cur.close()
            cls.__cur = None

    # 关闭数据库连接对象
    @classmethod
    def __close_connect(cls):
        if cls.__conn is not None:
            cls.__conn.close()
            cls.__conn = None


# 封装读取测试数据的方法
def read_json(filename):
    # 1.读取文件中的测试数据
    # 获取文件的路径
    file_path = app.BASE_PATH + "/data/" + filename + ".json"
    with open(file_path, encoding='utf-8')as f:
        data = json.load(f)
    print(data)
    # 2.转化为列表嵌套元组,进行结果返回
    list = []
    # 遍历获取到的文件,提取values值,并存进列表中
    for data_dict in data:
        data_tuple = tuple(data_dict.values())
        list.append(data_tuple)
    return list

# if __name__ == '__main__':
#     print(read_json("login_case_data"))
